import { login } from '@/api/user'
import { setToken, getToken, delToken } from '@/utils/storage'

export default {
  namespaced: true,
  state () {
    return {
      token: getToken() || ''
    }
  },
  mutations: {
    setUserToken (state, token) {
      // 1.1 存储token到vuex
      state.token = token
      // 1.2 持久化到本地
      setToken(token)
    },
    logout (state) {
      // 1.1 清除vuex中的token
      state.token = ''
      // 1.2 清除本地的token
      delToken()
    }
  },
  actions: {
    // 1. 登录
    async loginAction (context, obj) {
      // 1.1 发送请求
      const { data } = await login(obj)
      // 1.2 提交mutation
      context.commit('setUserToken', data.token)
    }
  },
  getters: {}
}
